import { useModel } from '@umijs/max';
import React, { useState, useRef, useEffect } from 'react';
import { Input, Avatar, List, Badge, Empty, message, Modal, Tooltip, Dropdown, Menu, Carousel } from 'antd';
import { SearchOutlined, PlusOutlined, CopyOutlined, BookOutlined, ShareAltOutlined, StarOutlined, StarFilled, EditOutlined, MoreOutlined } from '@ant-design/icons';
import icon from './icon.svg';
import ReactMarkdown from 'react-markdown';
import './assistant.css';
import './markdown.css';
import banner1 from '@/assets/img/luanbo1.jpeg';
import banner2 from '@/assets/img/luanbo2.jpeg';
import banner3 from '@/assets/img/luanbo3.jpeg';

const { TextArea } = Input;

// 消息类型定义
interface Message {
  type: 'text';
  content: string;
  user: {
    avatar: string;
    name: string;
    id: string;
  };
  createdAt: number;
  // 添加id用于动画追踪
  id: string;
  // 用于标记加载状态
  isLoading?: boolean;
  // 用于标记是否收藏
  isStarred?: boolean;
}

// 会话类型定义
interface Conversation {
  id: string;
  title: string;
  avatar: string;
  lastMessage: string;
  time: string;
  unreadCount: number;
  isNew?: boolean;
}

// 收藏项类型定义
interface StarredItem {
  id: string;
  messageId: string;
  conversationId: string;
  content: string;
  createdAt: number;
  conversationTitle: string;
}

const AssistantPage: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;
  const [inputValue, setInputValue] = useState('');
  const textareaRef = useRef<HTMLTextAreaElement>(null);
  const [selectedConversationId, setSelectedConversationId] = useState<string>('1');
  const [isMobileMenuOpen, setIsMobileMenuOpen] = useState<boolean>(false);
  const [starredItems, setStarredItems] = useState<StarredItem[]>([]);
  const [showStarredList, setShowStarredList] = useState(false);
  const [showShareModal, setShowShareModal] = useState(false);
  const [shareUrl, setShareUrl] = useState('');
  const [dropdownVisible, setDropdownVisible] = useState(false);
  const [currentConversationId, setCurrentConversationId] = useState('');
  const [editModalVisible, setEditModalVisible] = useState(false);
  const [editConversationTitle, setEditConversationTitle] = useState('');

  // 模拟会话列表数据
  const [conversations, setConversations] = useState<Conversation[]>([]);

  // 生成唯一ID的函数
  const generateId = () => {
    return Math.random().toString(36).substring(2, 11);
  };

  // 处理更多操作的函数
  const handleMoreActions = (conversationId: string) => {
    setCurrentConversationId(conversationId);
    setDropdownVisible(true);
  };

  // 编辑会话名称
  const handleEditConversation = (conversationId: string) => {
    const conversation = conversations.find(c => c.id === conversationId);
    if (conversation) {
      setEditConversationTitle(conversation.title);
      setCurrentConversationId(conversationId);
      setEditModalVisible(true);
    }
    setDropdownVisible(false);
  };

  // 保存编辑的会话名称
  const handleSaveEditTitle = () => {
    setConversations(conversations.map(conversation => 
      conversation.id === currentConversationId 
        ? { ...conversation, title: editConversationTitle }
        : conversation
    ));
    setEditModalVisible(false);
    message.success('会话名称已更新');
  };

  // 分享会话
  const handleShareConversation = (conversationId: string) => {
    // 这里可以实现会话分享的逻辑
    setShareUrl(`https://example.com/chat/${conversationId}`);
    setShowShareModal(true);
    setDropdownVisible(false);
  };

  // 删除会话
  const handleDeleteConversation = (conversationId: string) => {
    setConversations(conversations.filter(c => c.id !== conversationId));
    if (selectedConversationId === conversationId) {
      setSelectedConversationId(conversations.length > 1 ? conversations[0].id : '1');
    }
    message.success('会话已删除');
    setDropdownVisible(false);
  };

  // 菜单项配置
  const menuItems = [
    {
      key: 'edit',
      label: '编辑名称',
      onClick: () => handleEditConversation(currentConversationId),
    },
    {
      key: 'share',
      label: '分享',
      onClick: () => handleShareConversation(currentConversationId),
    },
    {
      key: 'delete',
      label: '删除',
      onClick: () => handleDeleteConversation(currentConversationId),
      danger: true,
    },
  ];

  // 下拉菜单配置

  // 使用useState管理消息列表，避免useMessages兼容性问题
  // 初始状态包含欢迎消息，当AI有实际回复时再过滤掉
  const [messages, setMessages] = useState<Message[]>([
    {
      type: 'text',
      content: '你好，我是AI助手！请问有什么可以帮助您的吗？',
      user: {
        avatar: icon,
        name: 'AI助手',
        id: 'ai',
      },
      createdAt: Date.now() - 1000 * 60,
      id: 'msg-welcome'
    },
  ]);

  // 模拟获取特定会话的消息
  const getConversationMessages = (conversationId: string): Message[] => {
    // 在实际应用中，这里应该是API调用
    // 这里简单模拟不同会话返回不同消息
    // 对于新创建的会话，显示欢迎消息
    if (conversationId.startsWith('new-')) {
      return [
        {
          type: 'text',
          content: '你好，我是AI助手！请问有什么可以帮助您的吗？',
          user: {
            avatar: icon,
            name: 'AI助手',
            id: 'ai',
          },
          createdAt: Date.now() - 1000 * 60,
          id: 'msg-welcome'
        },
      ];
    }
    
    // 对于已有记录的会话，返回空数组，实际的消息会在切换会话时被加载
    return [];
  };

  // 处理选择会话
  const handleSelectConversation = (conversationId: string) => {
    setSelectedConversationId(conversationId);
    // 加载该会话的消息
    setMessages(getConversationMessages(conversationId));
    // 在移动端下，选择会话后关闭侧边栏
    if (window.innerWidth < 768) {
      setIsMobileMenuOpen(false);
    }

    // 重置未读消息数
    setConversations(prevConversations =>
      prevConversations.map(conversation =>
        conversation.id === conversationId
          ? { ...conversation, unreadCount: 0 }
          : conversation
      )
    );
  };

  // 复制消息内容
  const copyMessage = (content: string) => {
    // 兼容旧浏览器
    if (navigator.clipboard && window.isSecureContext) {
      navigator.clipboard.writeText(content).then(() => {
        message.success('复制成功');
      }).catch(() => {
        message.error('复制失败');
        fallbackCopyTextToClipboard(content);
      });
    } else {
      // 降级方案
      fallbackCopyTextToClipboard(content);
    }
  };

  // 复制功能降级方案
  const fallbackCopyTextToClipboard = (text: string) => {
    const textArea = document.createElement('textarea');
    textArea.value = text;

    // 避免在某些移动设备上出现滚动条
    textArea.style.top = '0';
    textArea.style.left = '0';
    textArea.style.position = 'fixed';
    textArea.style.opacity = '0';

    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();

    try {
      const successful = document.execCommand('copy');
      message.success(successful ? '复制成功' : '复制失败');
    } catch (err) {
      message.error('复制失败');
    }

    document.body.removeChild(textArea);
  };

  // 切换消息收藏状态
  const toggleStar = (messageId: string) => {
    setMessages(prevMessages => {
      return prevMessages.map(msg => {
        if (msg.id === messageId) {
          const newIsStarred = !msg.isStarred;

          // 更新收藏列表
          if (newIsStarred) {
            const newStarredItem: StarredItem = {
              id: generateId(),
              messageId,
              conversationId: selectedConversationId || '',
              content: msg.content,
              createdAt: Date.now(),
              conversationTitle: conversations.find(c => c.id === selectedConversationId)?.title || ''
            };
            setStarredItems(prev => [...prev, newStarredItem]);
          } else {
            setStarredItems(prev => prev.filter(item => item.messageId !== messageId));
          }

          return { ...msg, isStarred: newIsStarred };
        }
        return msg;
      });
    });
  };

  // 分享消息
  const shareMessage = (content: string) => {
    const url = window.location.origin + window.location.pathname + `?share=${encodeURIComponent(content)}`;
    setShareUrl(url);
    setShowShareModal(true);
  };

  // 查看全部收藏
  const viewAllStarred = () => {
    setShowStarredList(true);
  };

  // 处理创建新会话
  const handleCreateNewConversation = () => {
    const newConversation: Conversation = {
      id: `new-${Date.now()}`,
      title: '新会话',
      avatar: icon,
      lastMessage: '开始新的对话吧！',
      time: '刚刚',
      unreadCount: 0,
      isNew: true
    };

    setConversations(prevConversations => [newConversation, ...prevConversations]);
    handleSelectConversation(newConversation.id);
  };

  // 监听窗口大小变化，在大屏幕上自动展开菜单
  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth >= 768) {
        setIsMobileMenuOpen(true);
      } else {
        setIsMobileMenuOpen(false);
      }
    };

    handleResize(); // 初始化
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // 组件初始化，加载默认会话的消息
  useEffect(() => {
    // 加载默认会话的消息
    setMessages(getConversationMessages(selectedConversationId));
  }, []);

  // 调用oneapi聊天接口发送消息
  const sendMessage = async (content: string) => {
    try {
      // 构建请求头
      const headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer sk-0iaPSx3TwJfkyNaWB282E93c26A641F6851756B8B8EcDd0b'
      };

      // 构建请求体
      const requestBody = {
        model: "qwen3-coder:30b",
        messages: [
          {
            role: "user",
            content: content
          }
        ],
        stream: true
      };

      // 发送POST请求到指定的API地址
      const response = await fetch('http://192.168.121.45:3000/v1/chat/completions', {
        method: 'POST',
        headers: headers,
        body: JSON.stringify(requestBody)
      });

      if (!response.ok) {
        throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
      }

      // 处理流式响应
      const reader = response.body?.getReader();
      if (!reader) {
        throw new Error('无法获取响应流');
      }

      const decoder = new TextDecoder();
      let accumulatedText = '';
      let aiMessageId = `msg-${Date.now()}`;
      let isFirstChunk = true;
      let isLoading = true;

      // 添加"正在输入..."的状态消息
      setMessages(prevMessages => [...prevMessages, {
        type: 'text',
        content: '正在输入...',
        user: {
          avatar: icon,
          name: 'AI助手',
          id: 'ai',
        },
        createdAt: Date.now(),
        id: aiMessageId,
        isLoading: true
      }]);

      while (true) {
        try {
          const { done, value } = await reader.read();
          if (done) break;

          const chunk = decoder.decode(value, { stream: true });

          // 解析SSE格式的响应
          const lines = chunk.split('\n');
          for (const line of lines) {
            const trimmedLine = line.trim();
            if (trimmedLine.startsWith('data: ')) {
              const dataStr = trimmedLine.slice(6);
              if (dataStr === '[DONE]') {
                // 处理完成信号
                isLoading = false;
                // 移除"正在输入..."状态
                setMessages(prevMessages =>
                  prevMessages.filter((msg: any) => !(msg.id === aiMessageId && msg.isLoading))
                );
                continue;
              }
              try {
                const data = JSON.parse(dataStr);
                if (data.choices && data.choices.length > 0) {
                  const delta = data.choices[0].delta;
                  if (delta.content) {
                    accumulatedText += delta.content;

                    // 更新消息内容
                    setMessages(prevMessages => {
                      // 如果是第一条数据，创建新消息并移除加载状态消息
                      if (isFirstChunk) {
                        isFirstChunk = false;
                        // 过滤掉加载状态消息和欢迎消息，然后添加实际消息
                        const filteredMessages = prevMessages.filter((msg: any) =>
                          !(msg.id === aiMessageId && msg.isLoading) && msg.id !== 'msg-welcome'
                        );
                        return [...filteredMessages, {
                          type: 'text',
                          content: accumulatedText,
                          user: {
                            avatar: icon,
                            name: 'AI助手',
                            id: 'ai',
                          },
                          createdAt: Date.now(),
                          id: aiMessageId
                        }];
                      }
                      // 否则更新已有消息
                      return prevMessages.map(msg =>
                        msg.id === aiMessageId
                          ? { ...msg, content: accumulatedText }
                          : msg
                      );
                    });

                    // 自动滚动到最新消息
                    setTimeout(() => {
                      const chatContent = document.querySelector('.chat-content');
                      if (chatContent) {
                        chatContent.scrollTop = chatContent.scrollHeight;
                      }
                    }, 10);
                  }
                }
              } catch (e) {
                console.error('解析JSON失败:', e);
              }
            }
          }
        } catch (streamError: any) {
          console.error('处理流数据时出错:', streamError);
          // 继续尝试读取，除非是严重错误
          if (!streamError.name || streamError.name !== 'AbortError') {
            break;
          }
        }
      }

      // 确保最终移除加载状态
      if (isLoading) {
        setMessages(prevMessages =>
          prevMessages.filter((msg: any) => !(msg.id === aiMessageId && msg.isLoading))
        );
      }

      // 确保消息不为空才更新会话列表
      if (accumulatedText.trim()) {
        // 更新会话列表中的最后消息
        setConversations(prevConversations =>
          prevConversations.map(conversation =>
            conversation.id === selectedConversationId
              ? {
                ...conversation,
                lastMessage: accumulatedText.length > 50
                  ? accumulatedText.substring(0, 50) + '...'
                  : accumulatedText,
                time: '刚刚',
                isNew: false
              }
              : conversation
          )
        );
      }
    } catch (error) {
      console.error('调用oneapi聊天接口失败:', error);
      message.error('发送消息失败，请稍后重试');

      // 发送失败时，添加一条错误消息提示用户
      setMessages(prevMessages => [...prevMessages, {
        type: 'text',
        content: '抱歉，AI回复暂时不可用，请稍后重试。',
        user: {
          avatar: icon,
          name: 'AI助手',
          id: 'ai',
        },
        createdAt: Date.now(),
        id: `msg-${Date.now()}`
      }]);
    }
  };

  // 重新生成AI消息
  const regenerateMessage = (messageId: string) => {
    // 找到当前AI消息在消息列表中的位置
    const messageIndex = messages.findIndex(msg => msg.id === messageId);
    if (messageIndex === -1) return;

    // 找到该AI消息前面最近的用户消息 - 简化逻辑
    let userMessageIndex = -1;
    for (let i = messageIndex - 1; i >= 0; i--) {
      if (messages[i].user.id === 'user') {
        userMessageIndex = i;
        break;
      }
    }

    if (userMessageIndex === -1) return;

    const userMessage = messages[userMessageIndex];

    // 删除当前AI消息
    setMessages(prevMessages => prevMessages.filter(msg => msg.id !== messageId));

    // 使用用户消息内容重新调用sendMessage
    sendMessage(userMessage.content);
  };

  // 编辑用户消息
  const editMessage = (content: string) => {
    setInputValue(content);
    // 聚焦到输入框
    textareaRef.current?.focus();
  };

  // 处理发送消息
  const handleSend = () => {
    if (!inputValue.trim()) return;

    // 添加用户消息，添加id用于动画追踪
    setMessages(prevMessages => [...prevMessages, {
      type: 'text',
      content: inputValue.trim(),
      user: {
        avatar: currentUser?.avatar || 'https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg',
        name: currentUser?.name || '用户',
        id: 'user',
      },
      createdAt: Date.now(),
      id: `msg-${Date.now()}`
    }]);

    // 清空输入框
    setInputValue('');

    // 更新会话列表中的最后消息
    setConversations(prevConversations =>
      prevConversations.map(conversation =>
        conversation.id === selectedConversationId
          ? {
            ...conversation,
            lastMessage: inputValue.trim(),
            time: '刚刚',
            title: conversation.isNew ? inputValue.trim().substring(0, 20) + (inputValue.trim().length > 20 ? '...' : '') : conversation.title,
            isNew: false
          }
          : conversation
      )
    );

    // 请求AI回复
    sendMessage(inputValue.trim());
  };

  // 处理键盘事件
  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSend();
    }
  };

  // 自定义渲染时间
  const customRenderTime = (timestamp: number) => {
    const date = new Date(timestamp);
    const now = new Date();
    const diffMs = now.getTime() - date.getTime();
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);

    if (diffMins < 1) {
      return '刚刚';
    } else if (diffMins < 60) {
      return `${diffMins}分钟前`;
    } else if (diffHours < 24) {
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${hours}:${minutes}`;
    } else if (diffDays < 7) {
      return `${diffDays}天前`;
    } else {
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${month}-${day}`;
    }
  };

  // 自定义渲染头像
  const customRenderAvatar = (props: any) => {
    const { avatar, user } = props;
    return (
      <Avatar
        src={user.id === 'ai' ? icon : avatar}
        alt={user.name}
        style={{ width: 36, height: 36 }}
        className="avatar-animation"
      />
    );
  };

  return (
    <div>
      <div
        title=""
        style={{
          display: 'flex',
          flexDirection: 'column',
          height: 'calc(100vh - 64px)',
          padding: 0,
        }}
      >
        <div className="chat-container">
          {/* 移动端菜单按钮 */}
          <div className="mobile-menu-toggle" onClick={() => setIsMobileMenuOpen(!isMobileMenuOpen)}>
            ☰
          </div>

          {/* 侧边栏会话列表 */}
          <div className={`chat-sidebar ${isMobileMenuOpen ? 'open' : ''}`}>
            {/* 侧边栏头部 */}
            <div className="sidebar-header">
              <h2 className="sidebar-title">会话</h2>
              <div className="sidebar-actions">
                <button
                  className="new-chat-btn animate-pulse"
                  onClick={handleCreateNewConversation}
                  title="创建新会话"
                >
                  <PlusOutlined />
                </button>
              </div>
            </div>
            <button
              className="conversation-item starred-header"
              onClick={viewAllStarred}
              style={{
                justifyContent: 'center',
                backgroundColor: '#FFF',
                fontSize: '14px',
                fontWeight: 500,
                border: 'none'
              }}
            >
              <BookOutlined style={{ marginRight: '8px' }} />
              全部收藏
            </button>

            {/* 搜索框 */}
            <div className="sidebar-search">
              <Input
                placeholder="搜索会话..."
                prefix={<SearchOutlined />}
                size="small"
                className="search-input"
              />
            </div>

            {/* 会话列表 */}
            <List
              className="conversation-list"
              itemLayout="horizontal"
              dataSource={conversations}
              renderItem={(conversation) => (
                <List.Item
                  onClick={() => handleSelectConversation(conversation.id)}
                  className={`conversation-item ${selectedConversationId === conversation.id ? 'active' : ''}`}
                  actions={[
                    <Badge count={conversation.unreadCount} style={{ backgroundColor: '#1890ff' }} />
                  ]}
                >
                  <List.Item.Meta
                    avatar={<Avatar src={conversation.avatar} />}
                    title={
                      <div className="conversation-title">
                        {conversation.title}
                      </div>
                    }
                    description={
                      <div className="conversation-description">
                        <span className="last-message">{conversation.lastMessage}</span>
                        <span className="message-time">{conversation.time}</span>
                       
                      </div>
                    }
                  />
                  <div className="more-icon-container">
                    <Dropdown
                      menu={{ items: menuItems }}
                      open={dropdownVisible && currentConversationId === conversation.id}
                      onOpenChange={(open) => {
                        if (open) {
                          setCurrentConversationId(conversation.id);
                        }
                        setDropdownVisible(open);
                      }}
                    >
                      <span className="ant-dropdown-link" style={{ cursor: 'pointer' }}>
                        <MoreOutlined />
                      </span>
                    </Dropdown>
                  </div>
                </List.Item>
              )}
              locale={{ emptyText: <Empty description="暂无会话" /> }}
            />
          </div>

          {/* 聊天主区域 */}
          <div className={`chat-main ${isMobileMenuOpen ? 'open' : ''}`}>
            {/* 轮播图区域 */}
            <div className="carousel-container" style={{ margin: 'auto', borderRadius: '8px', overflow: 'hidden',width:'700px' }}>
              <Carousel autoplay arrows dotPosition="bottom">
                <div>
                  <img 
                    src={banner1} 
                    alt="轮播图1" 
                    style={{ width: '100%', height: '200px', objectFit: 'cover' }}
                  />
                </div>
                <div>
                  <img 
                    src={banner2} 
                    alt="轮播图2" 
                    style={{ width: '100%', height: '200px', objectFit: 'cover' }}
                  />
                </div>
                <div>
                  <img 
                    src={banner3} 
                    alt="轮播图3" 
                    style={{ width: '100%', height: '200px', objectFit: 'cover' }}
                  />
                </div>
              </Carousel>
            </div>

            {/* 聊天内容区 */}
            <div className="chat-content">
              {messages.map((message) => (
                <div
                  key={message.id}
                  className={`msg-item ${message.user.id === 'ai' ? 'msg-ai' : 'msg-user'} animate-fade-in`}
                >
                  {message.user.id === 'ai' ? customRenderAvatar({ avatar: message.user.avatar, user: message.user }) : null}
                  <div className="msg-content-wrapper" style={{ marginLeft: message.user.id === 'ai' ? 20 : 0, marginRight: message.user.id === 'user' ? 20 : 0 }}>
                    <div className="msg-time">{customRenderTime(message.createdAt)}</div>
                    <div className="msg-content">
                      {message.isLoading ? (
                        <div className="typing-indicator">
                          <div className="typing-dot"></div>
                          <div className="typing-dot" style={{ animationDelay: '0.2s' }}></div>
                          <div className="typing-dot" style={{ animationDelay: '0.4s' }}></div>
                          <span className="typing-text">Typing 输入中</span>
                        </div>
                      ) : (
                        <>
                          <div className="markdown-body">
                            <ReactMarkdown>{message.content}</ReactMarkdown>
                          </div>
                                {/* 当消息不是第一条欢迎消息时才显示操作按钮 */}
                                {message.id !== 'msg-welcome' && (
                                  <div className="msg-actions">
                                    {/* AI消息按钮：复制、收藏、重新生成、分享 */}
                                    {message.user.id === 'ai' ? (
                                      <>
                                        <Tooltip title="复制">
                                          <button
                                            className="msg-action-btn"
                                            onClick={() => copyMessage(message.content)}
                                          >
                                            <CopyOutlined />
                                          </button>
                                        </Tooltip>
                                        <Tooltip title={message.isStarred ? "取消收藏" : "收藏"}>
                                          <button
                                            className="msg-action-btn"
                                            onClick={() => toggleStar(message.id)}
                                            style={{ color: message.isStarred ? '#ff9800' : 'inherit' }}
                                          >
                                            {message.isStarred ? <StarFilled /> : <StarOutlined />}
                                          </button>
                                        </Tooltip>
                                        <Tooltip title="重新生成">
                                  <button
                                    className="msg-action-btn"
                                    onClick={() => regenerateMessage(message.id)}
                                  >
                                    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                      <path d="M8 2V4M8 12V14M13.5 2.5L11.5 4.5M2.5 13.5L4.5 11.5M14 8H12M2 8H4M13.5 13.5L11.5 11.5M2.5 2.5L4.5 4.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                                    </svg>
                                  </button>
                                </Tooltip>
                                <Tooltip title="分享">
                                  <button
                                    className="msg-action-btn"
                                    onClick={() => shareMessage(message.content)}
                                  >
                                    <ShareAltOutlined />
                                  </button>
                                </Tooltip>
                              </>
                            ) : (
                              /* 用户消息按钮：复制、分享、编辑 */
                              <>
                                <Tooltip title="复制">
                                  <button
                                    className="msg-action-btn"
                                    onClick={() => copyMessage(message.content)}
                                  >
                                    <CopyOutlined />
                                  </button>
                                </Tooltip>
                                <Tooltip title="分享">
                                  <button
                                    className="msg-action-btn"
                                    onClick={() => shareMessage(message.content)}
                                  >
                                    <ShareAltOutlined />
                                  </button>
                                </Tooltip>
                                <Tooltip title="编辑">
                                  <button
                                    className="msg-action-btn"
                                    onClick={() => editMessage(message.content)}
                                  >
                                    <EditOutlined />
                                  </button>
                                </Tooltip>
                              </>
                            )}
                          </div>
                        )}
                        </>
                      )}
                    </div>
                  </div>
                  {message.user.id === 'user' ? customRenderAvatar({ avatar: message.user.avatar, user: message.user }) : null}
                </div>
              ))}
            </div>

            {/* 输入区域 */}
            <div className="chat-input-area">
              <div className="input-wrapper">
                <TextArea
                  ref={textareaRef}
                  value={inputValue}
                  onChange={(e) => setInputValue(e.target.value)}
                  onKeyDown={handleKeyDown}
                  placeholder="有问题，尽管问，shift+enter换行"
                  className="chat-textarea"
                  maxLength={1000}
                  showCount
                />
                <div className="input-actions">
                  <button
                    onClick={handleSend}
                    disabled={!inputValue.trim()}
                    className={`send-btn ${inputValue.trim() ? 'active' : ''}`}
                  >
                    发送
                  </button>
                </div>
              </div>
              <div className="input-hint">
                内容由AI生成，仅供参考
              </div>
            </div>
          </div>
        </div>
      </div>

      <Modal
        title="我的收藏"
        open={showStarredList}
        onCancel={() => setShowStarredList(false)}
        footer={null}
        width={600}
        height={400}
      >
        {starredItems.length === 0 ? (
          <div className="empty-state">
            <StarOutlined className="empty-state-icon" />
            <div className="empty-state-text">暂无收藏内容</div>
          </div>
        ) : (
          <List
            className="starred-list"
            dataSource={starredItems}
            renderItem={item => (
              <List.Item
                key={item.id}
                actions={[
                  <Tooltip title="复制">
                    <button
                      className="msg-action-btn"
                      onClick={() => copyMessage(item.content)}
                    >
                      <CopyOutlined />
                    </button>
                  </Tooltip>,
                  <Tooltip title="取消收藏">
                    <button
                      className="msg-action-btn"
                      onClick={() => {
                        // 从收藏列表移除
                        setStarredItems(prev => prev.filter(starred => starred.id !== item.id));
                        // 同时更新原消息的收藏状态
                        setMessages(prev => prev.map(msg =>
                          msg.id === item.messageId ? { ...msg, isStarred: false } : msg
                        ));
                      }}
                    >
                      <StarFilled style={{ color: '#ff9800' }} />
                    </button>
                  </Tooltip>
                ]}
              >
                <List.Item.Meta
                  title={<span className="conversation-title">{item.conversationTitle}</span>}
                  description={
                    <div>
                      <div className="last-message" style={{ marginBottom: '8px' }}>{item.content.length > 100 ? item.content.substring(0, 100) + '...' : item.content}</div>
                      <div className="message-time">
                        {new Date(item.createdAt).toLocaleString()}
                      </div>
                    </div>
                  }
                />
              </List.Item>
            )}
            style={{ maxHeight: '400px', overflowY: 'auto' }}
          />
        )}
      </Modal>

      <Modal
        title="分享消息"
        open={showShareModal}
        onCancel={() => setShowShareModal(false)}
        footer={[
          <button
            key="close"
            className="send-btn active"
            style={{ marginRight: '8px' }}
            onClick={() => setShowShareModal(false)}
          >
            关闭
          </button>
        ]}
      >
        <div style={{ marginBottom: '16px' }}>
          <p>复制以下链接分享给他人：</p>
          <Input
            value={shareUrl}
            readOnly
            suffix={
              <button
                className="header-action-btn"
                onClick={() => {
                  copyMessage(shareUrl);
                }}
              >
                <CopyOutlined />
              </button>
            }
          />
        </div>
      </Modal>

      {/* 编辑会话名称模态框 */}
      <Modal
        title="编辑会话名称"
        open={editModalVisible}
        onOk={handleSaveEditTitle}
        onCancel={() => setEditModalVisible(false)}
        okText="保存"
        cancelText="取消"
      >
        <Input
          value={editConversationTitle}
          onChange={(e) => setEditConversationTitle(e.target.value)}
          placeholder="请输入新的会话名称"
          maxLength={50}
          showCount
        />
      </Modal>
    </div>
  );
};

export default AssistantPage;